package com.example.smssender.contactimport.impl;

import android.content.Context;
import android.net.Uri;
import com.example.smssender.Contact;
import com.example.smssender.contactimport.ContactImporter;
import com.example.smssender.contactimport.ContactImportManager;
import com.example.smssender.contactimport.ImportResult;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * CSV 文件导入器
 */
public class CsvContactImporter implements ContactImporter {
    
    @Override
    public ImportResult importContacts(Context context, Uri source) {
        ImportResult result = new ImportResult();
        
        if (source == null) {
            result.setSuccess(false);
            result.addError("文件URI为空");
            return result;
        }
        
        try {
            InputStream inputStream = context.getContentResolver().openInputStream(source);
            if (inputStream == null) {
                result.setSuccess(false);
                result.addError("无法打开文件");
                return result;
            }
            
            List<Contact> contacts = parseCsvFile(context, source, inputStream);
            inputStream.close();
            
            // 验证和统计
            List<Contact> validContacts = new ArrayList<>();
            for (Contact contact : contacts) {
                if (ContactImportManager.validateContact(contact)) {
                    validContacts.add(contact);
                } else {
                    result.addError("无效数据：" + (contact.getName() != null ? contact.getName() : "未知"));
                }
            }
            
            result.setTotalCount(contacts.size());
            result.setSuccessCount(validContacts.size());
            result.setFailCount(contacts.size() - validContacts.size());
            result.setContacts(validContacts);
            result.setSuccess(true);
            
        } catch (Exception e) {
            result.setSuccess(false);
            result.addError("解析CSV文件失败：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 解析CSV文件
     */
    private List<Contact> parseCsvFile(Context context, Uri source, InputStream inputStream) throws Exception {
        List<Contact> contacts = new ArrayList<>();
        BufferedReader reader = null;
        
        try {
            // 尝试UTF-8编码
            reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            // 读取第一行测试编码是否正确
            reader.mark(10000); // 增加mark大小以支持更长的行
            String testLine = reader.readLine();
            if (testLine != null) {
                reader.reset();
            }
        } catch (Exception e) {
            // UTF-8读取失败，尝试GBK编码
            if (reader != null) {
                try { 
                    reader.close(); 
                } catch (Exception ignored) {}
            }
            if (inputStream != null) {
                try { 
                    inputStream.close(); 
                } catch (Exception ignored) {}
            }
            // 重新打开输入流
            inputStream = context.getContentResolver().openInputStream(source);
            if (inputStream != null) {
                reader = new BufferedReader(new InputStreamReader(inputStream, java.nio.charset.Charset.forName("GBK")));
            } else {
                throw new Exception("无法重新打开文件流");
            }
        }
        
        try {
            String line;
            boolean isFirstLine = true;
            int nameIndex = -1;
            int phoneIndex = -1;
            
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (line.isEmpty()) {
                    continue;
                }
                
                // 解析行数据
                String[] fields = parseCsvLine(line);
                
                if (isFirstLine) {
                    // 检测表头
                    nameIndex = findColumnIndex(fields, new String[]{"姓名", "名字", "name", "Name"});
                    phoneIndex = findColumnIndex(fields, new String[]{"手机号", "手机", "电话", "phone", "Phone", "phoneNumber", "mobile"});
                    
                    // 如果找到表头，跳过这一行
                    if (nameIndex >= 0 || phoneIndex >= 0) {
                        isFirstLine = false;
                        continue;
                    } else {
                        // 没有表头，假设第一列是姓名，第二列是手机号
                        nameIndex = 0;
                        phoneIndex = fields.length > 1 ? 1 : 0;
                    }
                    isFirstLine = false;
                }
                
                // 解析联系人数据
                if (fields.length > Math.max(nameIndex, phoneIndex)) {
                    String name = fields[nameIndex].trim();
                    String phone = fields[phoneIndex].trim();
                    
                    // 清理手机号
                    phone = ContactImportManager.normalizePhoneNumber(phone);
                    
                    if (!name.isEmpty() && !phone.isEmpty()) {
                        Contact contact = new Contact(name, phone);
                        contacts.add(contact);
                    }
                }
            }
        }
        finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception e) {
                    // 忽略关闭时的异常
                }
            }
        }
        
        return contacts;
    }
    
    /**
     * 解析CSV行（处理引号和逗号）
     */
    private String[] parseCsvLine(String line) {
        List<String> fields = new ArrayList<>();
        boolean inQuotes = false;
        StringBuilder currentField = new StringBuilder();
        
        for (int i = 0; i < line.length(); i++) {
            char c = line.charAt(i);
            
            if (c == '"') {
                inQuotes = !inQuotes;
            } else if ((c == ',' || c == ';' || c == '\t') && !inQuotes) {
                fields.add(currentField.toString());
                currentField = new StringBuilder();
            } else {
                currentField.append(c);
            }
        }
        
        fields.add(currentField.toString());
        return fields.toArray(new String[0]);
    }
    
    /**
     * 查找列索引
     */
    private int findColumnIndex(String[] fields, String[] possibleNames) {
        for (int i = 0; i < fields.length; i++) {
            String field = fields[i].trim().toLowerCase();
            for (String name : possibleNames) {
                if (field.equals(name.toLowerCase())) {
                    return i;
                }
            }
        }
        return -1;
    }
    
    @Override
    public String getName() {
        return "CSV文件导入";
    }
    
    @Override
    public String getDescription() {
        return "从CSV文件导入联系人，支持UTF-8和GBK编码";
    }
}

